package com.jwd.avmanager.util;

import com.jwd.avmanager.entity.SysUserinfo;
import com.jwd.avmanager.parse.ProtocolParserWS;
import com.jwd.avmanager.server.ClientManager;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 数据发送类
 */
public class ResponseSendUtil {
    private static Logger logger = LoggerFactory.getLogger(ResponseSendUtil.class);

    /**
     * 发送tcp数据
     *
     * @param msg
     * @param ctx
     */
    public static void   writeAndFlush(byte[] msg, ChannelHandlerContext ctx) {

//        DebugLogger.debug("回复信令"+ Arrays.toString(msg));
        if (ctx.isRemoved()){
            DebugLogger.err(logger,"writeAndFlush  ctx.isRemoved()");
            return;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        byte[]cmdData=new byte[2];
        byte[]cmdLen=new byte[4];
        System.arraycopy(msg,0,cmdData,0,2);
        System.arraycopy(msg,4,cmdLen,0,4);
        short cmd=ByteUtil.bytesToShort(cmdData);
        DebugLogger.info(ctx+ "回复信令长度" + msg.length+" cmd:"+cmd+"cmdLen:"+ByteUtil.bytesToInt(cmdLen));
        ChannelFuture channelFuture = ctx.writeAndFlush(msg);
        channelFuture.addListener((ChannelFutureListener) channelFuture1 -> {
            if (channelFuture1.isSuccess()) {
                DebugLogger.info(cmd+"发送成功");
            } else {

                DebugLogger.info(cmd+"发送失败");
            }
        });
    }

    /**
     * 通过webrtc协议发送
     * @param msg
     * @param ctx
     */
    public static void writeAndFlushWs(String msg, ChannelHandlerContext ctx){
        if (ctx.isRemoved()) {
            DebugLogger.err(logger,"writeAndFlushWs  ctx.isRemoved() msg： "+msg);
            return;
        }
        ctx.writeAndFlush(new TextWebSocketFrame(msg));
    }

    /**
     * 发送消息给所有调度台
     * @param parentGroup
     * @param str
     */
    public static void sendWsMessageToDispatcher(List<SysUserinfo> parentGroup, String str){

        if (parentGroup != null && parentGroup.size() != 0) {
            for (SysUserinfo sysUserinfo : parentGroup) {
                DebugLogger.info(sysUserinfo);
                ChannelHandlerContext webSocket = ClientManager.getInstance().getWebSocket(sysUserinfo.getUloginname());
                if (webSocket != null) {
                    DebugLogger.info("发送webSocket 给调度台");
                    webSocket.channel().writeAndFlush(new TextWebSocketFrame(str));
                }
            }
        }
    }
}
